package com.cherry.mybatis.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LongNullTypeHandler extends BaseTypeHandler<Long> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Long l, JdbcType jdbcType) throws SQLException {
        if (l == null) {
            preparedStatement.setLong(i, -1);
        } else {
            preparedStatement.setLong(i, l);
        }
    }

    @Override
    public Long getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return handleNullLong(resultSet.getLong(s));
    }

    @Override
    public Long getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return handleNullLong(resultSet.getLong(i));
    }

    @Override
    public Long getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return handleNullLong(callableStatement.getLong(i));
    }

    private Long handleNullLong(Long l) {
        return l == null ? -1 : l;
    }
}
